<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级名称" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择" clearable>
          <el-option
            v-for="course in courseList"
            :key="course.courseId"
            :label="course.courseName"
            :value="course.courseId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="校区" prop="campus">
        <el-select v-model="queryParams.campus" placeholder="请选择校区" clearable>
          <el-option
            v-for="dict in dict.type.campus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="教师" prop="teacherName">
        <el-input
          v-model="queryParams.teacherName"
          placeholder="请输入教师"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['classes:classes:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['classes:classes:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['classes:classes:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['classes:classes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="classesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="校区" align="center" prop="campus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.campus" :value="scope.row.campus"/>
        </template>
      </el-table-column>
      <el-table-column label="教室" align="center" prop="classroom" />
      <el-table-column label="最大学生人数" align="center" prop="maxStudents" />
      <el-table-column label="教师" align="center" prop="teacherName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['classes:classes:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['classes:classes:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleAddStudents(scope.row)"
          >添加学生</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handSelectStu(scope.row)"
          >查看班级学生</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改班级管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="课程名称" prop="courseName">
          <el-select v-model="form.courseName" placeholder="请选择" @change="onChange">
            <el-option
              v-for="course in courseList"
              :key="course.courseId"
              :label="course.courseName"
              :value="course.courseName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="校区" prop="campus">
          <el-select v-model="form.campus" placeholder="请选择校区">
            <el-option
              v-for="dict in dict.type.campus"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="教室" prop="classroom">
          <el-select v-model="form.classroom" placeholder="请选择" >
            <el-option
              v-for="classroom in classroomList"
              :key="classroom.classroomId"
              :label="classroom.classroomName"
              :value="classroom.classroomName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最大学生人数" prop="maxStudents">
          <el-input v-model="form.maxStudents" placeholder="请输入最大学生人数" />
        </el-form-item>
        <el-form-item label="教师id" prop="teacherId" style="display: none;">
          <el-input v-model="form.teacherId" placeholder="请输入教师id" />
        </el-form-item>
        <el-form-item label="教师" prop="teacherName">
          <el-select v-model="form.teacherName" placeholder="请选择" @change = "changeTeacher">
            <el-option
              v-for="teacher in teacherList"
              :key="teacher.userId"
              :label="teacher.nickName"
              :value="teacher.nickName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加学生对话框 -->
    <el-dialog :title="'为班级 ' + currentClass.className + ' 添加学生'" :visible.sync="studentDialogVisible" width="600px" append-to-body>
      <el-table
        :data="studentList"
        ref="studentTable"
        @selection-change="handleStudentSelectionChange"
        style="height: 400px; overflow-y: auto;"
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="校区" align="center" prop="campus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.campus" :value="scope.row.campus"/>
        </template>
      </el-table-column>
      <el-table-column label="英文名" align="center" prop="englishName" />
        <!-- 可以添加更多学生信息列 -->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="studentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSelectedStudents">提交</el-button>
      </div>
    </el-dialog>
       <!-- 查看学生对话框 -->
       <el-dialog :title="'查看班级学生'" :visible.sync="studentDialogVisible2" width="600px" append-to-body>
      <el-table
        :data="studentList2"
        ref="studentTable"
        @selection-change="handleStudentSelectionChange2"
        style="height: 400px; overflow-y: auto;"
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生姓名" align="center" prop="name" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="校区" align="center" prop="campus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.campus" :value="scope.row.campus"/>
        </template>
      </el-table-column>
      <el-table-column label="英文名" align="center" prop="englishName" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="studentDialogVisible2 = false">取消</el-button>
        <el-button type="primary" @click="submitdeleteStudents">退班</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClasses, getClasses, delClasses, addClasses, updateClasses, addClassForStu, getStuWithClass, exitClass } from "@/api/classes/classes";
import { listCourses } from "@/api/course/courses";
import { listClassroom } from "@/api/classroom/classroom";
import { listUser } from "@/api/system/user";
import { listInfo1 } from "@/api/student/info"; // 假设存在获取学生列表的接口

export default {
  name: "Classes",
  dicts: ['campus'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班级管理表格数据
      classesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      teacherList: [],
      teacherParams: {
        pageNum: 1,
        pageSize: 100,
      },
      classroomList: [],
      classroomParam: {
        pageNum: 1,
        pageSize: 10,
        classroomNumber: null,
        classroomName: null,
        buildingName: null,
        floor: null,
        classroomType: null
      },
      courseList: [],
      courseParam: {
        pageNum: 1,
        pageSize: 100,
        courseType: null,
        year: null,
        semester: null,
        subject: null,
        classType: null,
        grade: null,
        courseName: null
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        className: null,
        courseId: null,
        courseName: null,
        campus: null,
        classroom: null,
        maxStudents: null,
        teacherId: null,
        teacherName: null,
        courseId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        campus: [
          { required: true, message: "校区不能为空", trigger: "change" }
        ],
        classroom: [
          { required: true, message: "教室不能为空", trigger: "blur" }
        ],
        maxStudents: [
          { required: true, message: "最大学生人数不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "教师id不能为空", trigger: "blur" }
        ],
        teacherName: [
          { required: true, message: "教师不能为空", trigger: "blur" }
        ]
      },
      studentDialogVisible: false,
      studentDialogVisible2: false,
      studentList: [],
      studentList2: [],
      selectedStudents: [],
      currentClass: {}
    };
  },
  created() {
    this.getList();
    this.getCourses();
    this.getClassroomS();
    this.getUsers();
  },
  methods: {
    getUsers() {
      listUser(this.teacherParams).then(response => {
        this.teacherList = response.rows;
      });
    },
    getClassroomS() {
      listClassroom(this.classroomParam).then(response => {
        this.classroomList = response.rows;
      });
    },
    onChange(selectedName) {
      const selectedCourse = this.courseList.find(course => course.courseName === selectedName);
      if (selectedCourse) {
        this.form.courseId = selectedCourse.courseId;
      }
    },
    changeTeacher(selectedName) {
      const selectedTeacher = this.teacherList.find(teacher => teacher.nickName === selectedName);
      console.log(selectedTeacher);
      if (selectedTeacher) {
        this.form.teacherId = selectedTeacher.userId;
      }
    },
    getCourses() {
      listCourses(this.courseParam).then(response => {
        this.courseList = response.rows;
        console.log(this.courseList);
      });
    },
    getStudents() {
    getStuWithClass(this.currentClass.classId)
      .then(response => {
            console.log("返回的数据", response.rows);
            const studentIds = response.rows.map(item => item.studentId);
            console.log("ids",studentIds)
            return listInfo1(studentIds);
        })
      .then(response => {
        console.log(response.rows)
            this.studentList = response.rows;
            console.log(this.studentList,"ssss")
        })
      .catch(error => {
            console.error('发生错误:', error);
        });
    },
    getStudents2(){
      getStuWithClass(this.currentClass.classId).then(response => {
        this.studentList2 = response.rows;
        console.log("获取学生列表", response.rows,this.currentClass.classId)
      });
    },
    /** 查询班级管理列表 */
    getList() {
      this.loading = true;
      listClasses(this.queryParams).then(response => {
        this.classesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        classId: null,
        className: null,
        courseId: null,
        courseName: null,
        campus: null,
        classroom: null,
        maxStudents: null,
        teacherId: null,
        teacherName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classId);
      this.single = selection.length!== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const classId = row.classId || this.ids;
      getClasses(classId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班级管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classId != null) {
            updateClasses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClasses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classIds = row.classId || this.ids;
      this.$modal.confirm('是否确认删除班级管理编号为"' + classIds + '"的数据项？').then(function() {
        return delClasses(classIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('classes/classes/export', {
        ...this.queryParams
      }, `classes_${new Date().getTime()}.xlsx`);
    },
    handleAddStudents(row) {
      this.currentClass = row;
      this.getStudents()
      this.studentDialogVisible = true;
    },
    handSelectStu(row){
      this.currentClass = row;
      console.log("获取班级")
      this.getStudents2()
      this.studentDialogVisible2 = true;

    },
    handleStudentSelectionChange(selection) {
      this.selectedStudents = selection;
    },
    handleStudentSelectionChange2(selection) {
      this.selectedStudents = selection;
    },
    submitSelectedStudents() {
      // 这里添加实际提交选中学生到班级的逻辑，例如调用接口
      this.studentDialogVisible = false;
      const result = this.selectedStudents.map(student => {
        return {
          studentId: student.studentId,
          classId: this.currentClass.classId
        };

      });
      console.log(result)
      addClassForStu(result).then(response =>{
        this.$modal.msgSuccess("添加成功");
      })
    },
    submitdeleteStudents(){
      const result = this.selectedStudents.map(student => {
        return {
          studentId: student.studentId,
          classId: this.currentClass.classId
        };

      });
      console.log(result)
      exitClass(result).then(response =>{
        this.$modal.msgSuccess("退班成功");
        this.studentList = []
        this.studentDialogVisible2 = false
      })
    }
  }
};
</script>